package contest.controller;

import contest.util.ErrorLog;
import contest.util.ResPathConstant;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class WebAuthorize extends WebInit implements ServletConfig {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            if (isAuthorize(request, response)) {
                this.loadRequest(request);
                this.processRequest(request, response);
            } else {
                //LOGIN IS RETURNED
            }
        } catch (Exception ex) {
            ErrorLog.catchException(ResPathConstant.ERROR_LOG_TXT, (Exception) ex);
            forward("/error?code=" + getServletContext().getInitParameter("code-error-page"), request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    //CHECK AUTHORIZATION OF USER
    protected Boolean isAuthorize(HttpServletRequest request, HttpServletResponse response) {
        if (sessionProcess.getAttribute("USER_ID") != null) {
            if (WebInit.AUTHORIZE_PAGE != null && sessionProcess.getAttribute("ROLE_ID") != null) {
                String[] list = WebInit.AUTHORIZE_PAGE.get(sessionProcess.getAttribute("ROLE_ID").toString());
                String pathCurrent = this.getServletName();
                if (list != null) {
                    Boolean isAllow = false;
                    for (int i = 0; !isAllow && i < list.length; i++) {
                        if (list[i].equals(pathCurrent)) {
                            isAllow = true;
                        }
                    }
                    return isAllow;
                }
            }
            return true;
        }
        return false;
    }
}
